package com.liusand.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @author :liusha
 * packageName :com.liusand.common.utils
 * fileName :DateUtils
 * creationTime :2022/12/20 16:25
 */
public class Utils {
    private static final String SECONDS_AGO_SUFFIX = "秒前";
    private static final String MINUTES_AGO_SUFFIX = "分钟前";
    private static final String HOURS_AGO_SUFFIX = "小时前";
    private static final DateTimeFormatter DAYS_AGO_FORMAT = DateTimeFormatter.ofPattern("MM-dd");
    private static final DateTimeFormatter YEARS_AGO_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter SPECIFIC_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter TIME_OF_YEAR_FORMAT = DateTimeFormatter.ofPattern("MM-dd HH:mm");

    public static Integer birthday2age(String birthday){
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date tmp = null;
        try {
            tmp = dateFormat.parse(birthday);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        Calendar birth = Calendar.getInstance();
        birth.setTime(tmp);
        int age;
        if (birth.after(now)) {
            age = 0;
        } else {
            age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
            if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                age += 1;
            }
        }
        return age;
    }

    public static Integer getScore(Integer userAge, Integer userAge2){
        return userAge - userAge2;
    }

    public static String timeConvert(LocalDateTime time){
        LocalDateTime now = LocalDateTime.now();
        if (time.compareTo(now) >= 0){
            return time.format(SPECIFIC_FORMAT);
        }
        Duration duration = Duration.between(time, now);
        if (time.getYear() < now.getYear()){
            return time.format(YEARS_AGO_FORMAT);
        }
        if (duration.toDays() > 0){
            return time.format(DAYS_AGO_FORMAT);
        }
        if (duration.toHours() > 0){
            return duration.toHours() + HOURS_AGO_SUFFIX;
        }
        if (duration.toMinutes() > 0){
            return duration.toMinutes() + MINUTES_AGO_SUFFIX;
        }
        if (duration.getSeconds() > 0){
            return duration.getSeconds() + SECONDS_AGO_SUFFIX;
        }
        return time.format(SPECIFIC_FORMAT);
    }
}
